package com.wang.service.impl;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.junit.Before;
import org.junit.Test;

public class MongoDatabaseTest {

    private MongoDatabase db_customer;
    private MongoCollection<Document> tb_customer;
    private MongoClient client;

    @Before
    public void init(){
       //连接mongodb服务区
        client=new MongoClient("127.0.0.1",27017);
        //选择数据库
        db_customer=client.getDatabase("db_customer");
        //选择集合
        tb_customer=db_customer.getCollection("tb_customer");

    }

    @Test
    public void insertOne() {
        Document document = new Document();
        document.append("id",2);
        document.append("name","王宇鑫");
        document.append("age",22);
        document.append("work","吹牛逼");
        tb_customer.insertOne(document);
        System.out.println(document);
    }
    //修改符合条件的第一条数据
    @Test
    public void updateOne(){
        tb_customer.updateOne(Filters.eq("name","王宇鑫"),
                new Document("$set",new Document("name","武松1")));

    }

    //修改符合条件的所有记录
    @Test
    public void updateMany(){
        tb_customer.updateMany(
                Filters.eq("name","武松1"),
                new Document("$set",new Document("name","武松666"))
        );

    }

    @Test
    public void findAll(){
        FindIterable<Document> documents = tb_customer.find();
        for (Document document : documents) {
            System.out.println(document);
        }

    }
    //条件查询
    @Test
    public void findQuery(){
        FindIterable<Document> documents = tb_customer.find(Filters.eq("name", "武松666"));
        for (Document document : documents) {
            System.out.println(document);
        }
    }

    //and条件查询
    @Test
    public void findQueryMulti(){
        BasicDBObject doc5 = new BasicDBObject();
        doc5.put("age",22);
        doc5.put("name","武松666");
        FindIterable<Document> documents = tb_customer.find(doc5);
        for (Document document : documents) {
            System.out.println(document);
        }

    }


}
